{% extends "base.html" %}
{% block head %}

    <script src="https://cdn.jsdelivr.net/npm/mermaid@10.9.0/dist/mermaid.min.js"></script>
    

    <script>
        // 初始化 Mermaid，但延迟执行直到页面完全加载
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof mermaid !== 'undefined') {
                mermaid.initialize({ 
                    startOnLoad: false,
                    theme: 'default',
                    securityLevel: 'loose',
                    fontFamily: 'Arial, sans-serif'
                });
                console.log('Mermaid 初始化成功');
            } else {
                console.error('Mermaid 未定义，加载失败');
            }
        });
    </script>
    
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/ext-language_tools.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/mode-text.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.0/theme-chrome.js"></script>
    
    <style>
        .editor-container {
            display: flex;
            height: 70vh;
            gap: 20px;
            margin-top: 20px;
        }
        .code-editor-container {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-height: 400px;
            position: relative;
            overflow: hidden;
        }
        #code-editor {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            font-size: 16px !important;
        }
        .preview-pane {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            overflow: auto;
            min-height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f9fa;
        }
        .mermaid-toolbar {
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .alert-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 2000;
            min-width: 300px;
        }
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
        }
        .empty-preview {
            color: #6c757d;
            text-align: center;
            padding: 20px;
        }
        
        .ace_editor {
            position: relative !important;
            height: 100% !important;
            width: 100% !important;
        }
        
  
        body {
            -webkit-user-select: auto !important;
            -moz-user-select: auto !important;
            -ms-user-select: auto !important;
            user-select: auto !important;
        }
    </style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="alert-container" id="alert-container"></div>
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>{{ title }}</h2>
        <div>
            <button class="btn btn-outline-secondary" id="help-btn">
                <i class="bi bi-question-circle"></i> 帮助
            </button>
        </div>
    </div>
    
    <div class="card">
        <div class="card-body">
            <div class="mb-4">
                <label class="form-label fw-bold">图表标题</label>
                <input type="text" id="diagram-title" class="form-control form-control-lg" 
                       value="{{ diagram.title if diagram else '未命名图表' }}" 
                       placeholder="请输入图表标题">
            </div>
            
            <div class="mermaid-toolbar">
                <div class="btn-group">
                    <button class="btn btn-primary" id="preview-btn">
                        <i class="bi bi-eye me-1"></i> 预览图表
                    </button>
                    <button class="btn btn-success" id="save-btn">
                        <i class="bi bi-save me-1"></i> 保存图表
                    </button>
                </div>
                <div>
                    <button class="btn btn-outline-danger" id="reset-btn">
                        <i class="bi bi-arrow-counterclockwise"></i> 重置
                    </button>
                </div>
            </div>
            
            <div class="editor-container">
                <div class="code-editor-container" style="height: 100%;">
                    <div id="code-editor"></div>
                    <div class="loading-overlay" id="editor-loading">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2">编辑器加载中...</p>
                        </div>
                    </div>
                </div>
                <div id="preview-pane" class="preview-pane">
                    <div class="empty-preview">
                        <i class="bi bi-diagram-3" style="font-size: 3rem;"></i>
                        <h5 class="mt-3">图表预览区</h5>
                        <p class="text-muted">编辑Mermaid代码后，点击"预览图表"按钮查看效果</p>
                        <button class="btn btn-outline-primary mt-2" id="initial-preview-btn">
                            <i class="bi bi-eye me-1"></i> 点击预览
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h5>Mermaid 语法参考</h5>
                    <a href="https://mermaid.js.org/syntax/entityRelationshipDiagram.html" 
                       target="_blank" class="btn btn-sm btn-link">
                        完整文档 <i class="bi bi-box-arrow-up-right"></i>
                    </a>
                </div>
                <div class="card">
                    <div class="card-body">
                        <pre id="syntax-help" class="p-3 bg-light rounded"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 初始化数据
    const diagramData = {
        id: "{{ diagram.id if diagram else '' }}",
        req_id: "{{ req_id }}",
        type: "{{ diagram_type }}",
        title: "{{ diagram.title if diagram else '' }}",
        mermaid_code: `{{ diagram.mermaid_code | safe if diagram and diagram.mermaid_code else '' }}`
    };
    
    // 获取CSRF令牌
    let csrfToken = null;
    try {
        csrfToken = "{{ csrf_token() }}";
        if (!csrfToken || csrfToken === 'undefined') {
            throw new Error('CSRF令牌未定义');
        }
    } catch (error) {
        console.error('获取CSRF令牌失败:', error);
        showAlert('安全警告：无法获取CSRF令牌，请刷新页面重试', 'danger');
    }

    // 显示提示消息
    function showAlert(message, type = 'success') {
        const alertContainer = document.getElementById('alert-container');
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
        alertContainer.appendChild(alert);
        
        // 自动关闭
        setTimeout(() => {
            alert.remove();
        }, 5000);
    }

    // 初始化编辑器
    let editor = null;
    
    function initEditor() {
        // 确保编辑器元素存在
        const editorElement = document.getElementById('code-editor');
        if (!editorElement) {
            console.error('编辑器元素未找到');
            showAlert('编辑器初始化失败：找不到编辑器元素', 'danger');
            return;
        }
        
        try {
            // 创建Ace编辑器
            editor = ace.edit("code-editor");
            
            // 设置编辑器选项
            editor.setTheme("ace/theme/chrome");
            editor.session.setMode("ace/mode/text");
            editor.setFontSize(16);
            editor.setOptions({
                enableBasicAutocompletion: true,
                enableLiveAutocompletion: true,
                enableSnippets: true,
                showPrintMargin: false,
                highlightActiveLine: true,
                showLineNumbers: true,
                showGutter: true
            });
            
            // 设置初始代码
            if (diagramData.mermaid_code && diagramData.mermaid_code.trim() !== '') {
                editor.setValue(diagramData.mermaid_code);
            } else {
                // 根据类型设置模板
                const template = getTemplateByType(diagramData.type);
                editor.setValue(template);
            }
            
            editor.clearSelection();
            editor.gotoLine(0);
            
            // 调整编辑器大小以适应容器
            editor.resize();
            
            // 隐藏加载状态
            document.getElementById('editor-loading').style.display = 'none';
            
            console.log('编辑器初始化成功');
            
            // 初始预览（延迟执行）
            setTimeout(() => {
                previewDiagram();
            }, 300);
            
        } catch (error) {
            console.error('编辑器初始化失败:', error);
            document.getElementById('editor-loading').innerHTML = `
                <div class="text-center text-danger">
                    <i class="bi bi-exclamation-triangle-fill" style="font-size: 2rem;"></i>
                    <h5 class="mt-2">编辑器初始化失败</h5>
                    <p>${error.message}</p>
                    <button class="btn btn-primary mt-2" onclick="location.reload()">
                        <i class="bi bi-arrow-repeat"></i> 重新加载
                    </button>
                </div>
            `;
        }
    }
    
    // 获取模板
    function getTemplateByType(type) {
        switch(type) {
            case 'erd':
                return `erDiagram
    CUSTOMER {
        string name
        string email
        date createdAt
    }
    ORDER {
        int orderId PK
        date orderDate
        string status
    }
    PRODUCT {
        int productId PK
        string name
        decimal price
    }
    
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ ORDER_LINE : contains
    ORDER_LINE }|--|| PRODUCT : includes`;
                
            case 'sequence':
                return `sequenceDiagram
    participant User as 用户
    participant System as 系统
    participant DB as 数据库
    
    User->>System: 登录请求
    System->>DB: 查询用户信息
    DB-->>System: 返回用户数据
    alt 验证成功
        System-->>User: 显示欢迎页面
    else 验证失败
        System-->>User: 显示错误信息
    end`;
                
            case 'flowchart':
                return `flowchart TD
    A[开始] --> B{条件判断}
    B -->|条件1| C[执行操作1]
    B -->|条件2| D[执行操作2]
    C --> E[结束]
    D --> E
    E --> F>流程结束]`;
                
            default:
                return `graph TD
    A[开始] --> B[处理步骤]
    B --> C{决策点}
    C -->|是| D[执行操作]
    C -->|否| E[其他操作]
    D --> F[结束]
    E --> F`;
        }
    }
    
    // 预览图表
    function previewDiagram() {
        const previewPane = document.getElementById('preview-pane');
        const code = editor ? editor.getValue() : '';
        
        // 清空预览区
        previewPane.innerHTML = '<div class="text-center p-5"><div class="spinner-border text-primary"></div><p class="mt-2">渲染图表中...</p></div>';
        
        try {
            // 确保Mermaid已加载
            if (typeof mermaid === 'undefined') {
                throw new Error('Mermaid库未加载');
            }
            
            // 使用requestAnimationFrame确保DOM更新后执行
            requestAnimationFrame(() => {
                try {
                    mermaid.render('mermaid-preview', code, (svgCode) => {
                        previewPane.innerHTML = `
                            <div class="mermaid-preview-container">
                                ${svgCode}
                                <div class="mt-3 text-center">
                                    <button class="btn btn-sm btn-outline-secondary" onclick="showMermaidCode()">
                                        <i class="bi bi-code"></i> 查看源代码
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                } catch (renderError) {
                    console.error('图表渲染错误:', renderError);
                    previewPane.innerHTML = `
                        <div class="alert alert-danger">
                            <h5><i class="bi bi-exclamation-triangle"></i> 渲染错误</h5>
                            <p>${renderError.message}</p>
                            <button class="btn btn-sm btn-outline-primary mt-2" onclick="previewDiagram()">
                                <i class="bi bi-arrow-repeat"></i> 重新尝试
                            </button>
                        </div>
                    `;
                }
            });
        } catch (e) {
            previewPane.innerHTML = `
                <div class="alert alert-danger">
                    <h5><i class="bi bi-exclamation-triangle"></i> 严重错误</h5>
                    <p>${e.message}</p>
                    <p>请检查Mermaid代码语法</p>
                </div>
            `;
        }
    }
    
    // 显示Mermaid代码
    function showMermaidCode() {
        if (!editor) {
            alert('编辑器未初始化');
            return;
        }
        const code = editor.getValue();
        alert(`当前图表Mermaid代码:\n\n${code}`);
    }
    
    // 保存图表
    function saveDiagram() {
        if (!editor) {
            showAlert('编辑器未初始化，无法保存', 'danger');
            return;
        }
        
        const saveBtn = document.getElementById('save-btn');
        const originalHtml = saveBtn.innerHTML;
        
        // 显示保存状态
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 保存中...';
        
        const titleInput = document.getElementById('diagram-title');
        const title = titleInput.value.trim() || `未命名${getDiagramTypeName(diagramData.type)}图`;
        
        const diagramPayload = {
            id: diagramData.id || undefined,
            req_id: diagramData.req_id,
            type: diagramData.type,
            title: title,
            code: editor.getValue()
        };
        
        // 更新标题
        titleInput.value = title;
        
        // 发送保存请求
        fetch("{{ url_for('diagram.save_diagram') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify(diagramPayload)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                // 更新ID以便后续编辑
                if (data.id) diagramData.id = data.id;
                
                showAlert('图表保存成功!', 'success');
                
                // 自动关闭窗口（可选）
                setTimeout(() => {
                    if (window.opener && !window.opener.closed) {
                        window.opener.location.reload();
                    }
                    window.close();
                }, 2000);
            } else {
                throw new Error(data.message || '服务器返回未知错误');
            }
        })
        .catch(error => {
            console.error('保存失败:', error);
            showAlert(`保存失败: ${error.message}`, 'danger');
        })
        .finally(() => {
            // 恢复按钮状态
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalHtml;
        });
    }
    
    // 获取图表类型名称
    function getDiagramTypeName(type) {
        const names = {
            'erd': '实体关系',
            'sequence': '时序交互',
            'flowchart': '业务流程'
        };
        return names[type] || '';
    }
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 确保DOM完全加载后初始化编辑器
        setTimeout(() => {
            initEditor();
        }, 100);
        
        // 设置语法帮助
        document.getElementById('syntax-help').textContent = 
            diagramData.type === 'erd' ? `erDiagram
    ENTITY1 {
        type field1 PK
        type field2
    }
    ENTITY2 {
        type field3 PK
        type field4
    }
    
    ENTITY1 ||--o{ ENTITY2 : "关系描述"` : 
            diagramData.type === 'sequence' ? `sequenceDiagram
    participant A as 参与者A
    participant B as 参与者B
    
    A->>B: 请求消息
    B-->>A: 响应消息` : 
            `flowchart TD
    A[开始] --> B{条件}
    B -->|是| C[操作1]
    B -->|否| D[操作2]`;
        
        // 事件监听
        document.getElementById('preview-btn').addEventListener('click', previewDiagram);
        document.getElementById('initial-preview-btn').addEventListener('click', previewDiagram);
        document.getElementById('save-btn').addEventListener('click', saveDiagram);
        document.getElementById('reset-btn').addEventListener('click', function() {
            if (confirm('确定要重置编辑器内容吗？') && editor) {
                const template = getTemplateByType(diagramData.type);
                editor.setValue(template);
                editor.clearSelection();
                previewDiagram();
            }
        });
        document.getElementById('help-btn').addEventListener('click', function() {
            alert('使用帮助:\n1. 在左侧编辑Mermaid代码\n2. 点击"预览图表"查看效果\n3. 点击"保存图表"保存结果\n\n快捷键:\n- Ctrl+S: 保存\n- Ctrl+Enter: 预览');
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', function(e) {
            // Ctrl+S 保存
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                saveDiagram();
            }
            
            // Ctrl+Enter 预览
            if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                e.preventDefault();
                previewDiagram();
            }
        });
    });
</script>
{% endblock %}